Skip to content

conda目录移动后的bin可执行脚本路径修复

python
#!/bin/env python
import glob
from pathlib import Path
import subprocess
import argparse

def sub_script_exec_head(dst_dir, sed_pattern):
    f_list = glob.glob(f"{dst_dir}/*", recursive=True)
    for f_path in f_list:
        try:
            out_bytes = subprocess.check_output(['file', f_path])
            output = out_bytes.decode("utf8")
            if "script, ASCII" not in output:
                continue
            cmd = f"sed -i '{sed_pattern}' {f_path}"
            print(f"{cmd}")
            subprocess.check_output(cmd, shell=True)
        except subprocess.CalledProcessError as e:
            out_bytes = e.output       # Output generated before error
            code      = e.returncode   # Return code

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--conda-root", required=True, type=str, help="conda root dir")
    parser.add_argument("--old-root", required=True, type=str, help="old root dir that will be replace with conda-root")
    parser.add_argument("--only-env", required=False, type=bool, default=True, help="only fix env bin file")
    opt = parser.parse_args()

    conda_root = opt.conda_root
    old_root = opt.old_root

    envs_list = [str(x) for x in Path(f"{conda_root}/envs").glob("*") if x.is_dir()]
    dir_list = envs_list
    if not opt.only_env:
        dir_list += [f"{conda_root}"]
    else:
        print(f"only envs root need to be fixed. ignore {conda_root}/bin")
    
    sed_pattern = f"s#{old_root}#{conda_root}#g"
    for dir_path in dir_list:
        dst_dir = Path(f"{dir_path}/bin")
        if not dst_dir.exists():
            print(f"{dst_dir} not exists")
            continue
        sub_script_exec_head(dst_dir, sed_pattern=sed_pattern)